/*
 * @lc app=leetcode.cn id=54 lang=cpp
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        int top = 0;
        int left = 0;
        int bottom = m - 1;
        int right = n - 1;
        vector<int> res;
        while (res.size() < m * n) {
            for (int i = left; i <= right && res.size() < m * n; i++) {
                res.emplace_back(matrix[top][i]);
            }
            top++;

            for (int i = top; i <= bottom && res.size() < m * n; i++) {
                res.emplace_back(matrix[i][right]);
            }
            right--;

            for (int i = right; i >= left && res.size() < m * n; i--) {
                res.emplace_back(matrix[bottom][i]);
            }
            bottom--;

            for (int i = bottom; i >= top && res.size() < m * n; i--) {
                res.emplace_back(matrix[i][left]);
            }
            left++;
            
        }
        return res;
    }
};
// @lc code=end

